<!--
 * @Description: 项目列表--新增、编辑弹窗
 * @Author: Caroline
 * @Date: 2024-01-16 20:06:43
 * @LastEditTime: 2024-03-12 13:36:53
 * @LastEditors: Caroline
 * @FilePath: \Evaluation-web\src\views\project\add-or-update.vue
-->
<template>
  <el-dialog v-model="visible" width="700px" :title="isDetail ? $t('detail') : isEdit ? $t('update') : $t('add')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" :class="{ isDetail: isDetail }" :label-position="isDetail ? 'right' : 'top'" :inline="true" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()" :label-width="isDetail ? '' : '120px'">
      <!-- 项目名 -->
      <el-form-item prop="name" :label="$t('project.name') + labelSuffix">
        <div v-if="isDetail">{{ dataForm.name }}</div>
        <el-input v-else v-model="dataForm.name" :placeholder="$t('project.name')"></el-input>
      </el-form-item>

      <!-- 区域 -->
      <el-form-item prop="area" :label="$t('project.area') + labelSuffix">
        <div v-if="isDetail">{{ dataForm.fullAreaName }}</div>
        <el-cascader v-else ref="areaRef" v-model="dataForm.fullAreaId" @change="onAreaChange" :placeholder="$t('project.area')" filterable clearable :props="{ checkStrictly: true }" :options="areaList" />
      </el-form-item>

      <!-- 项目负责人 -->
      <el-form-item prop="director" :label="$t('project.director') + labelSuffix">
        <div v-if="isDetail">{{ dataForm.director.name }}</div>
        <el-select v-else v-model="dataForm.director" value-key="id" :placeholder="$t('project.director')">
          <el-option v-for="item in directorList" :key="item.id" :label="item.name" :value="item"></el-option>
        </el-select>
      </el-form-item>

      <!-- 联系方式 -->
      <el-form-item prop="directorConnect" :label="$t('project.directorConnect') + labelSuffix">
        <div v-if="isDetail">{{ dataForm.directorConnect }}</div>
        <el-input v-else v-model="dataForm.directorConnect" :placeholder="$t('project.directorConnect')"></el-input>
      </el-form-item>

      <!-- 项目金额（元） -->
      <el-form-item prop="price" :label="$t('project.price') + labelSuffix">
        <div v-if="isDetail">{{ dataForm.price }}/元</div>
        <el-input v-else v-model="dataForm.price" :placeholder="$t('project.price')">
          <template #append>元</template>
        </el-input>
      </el-form-item>

      <!-- 开票单位 -->
      <el-form-item prop="invoicedUnit" :label="$t('project.invoicedUnit') + labelSuffix">
        <div v-if="isDetail">{{ dataForm.invoicedUnit }}</div>
        <el-input v-else v-model="dataForm.invoicedUnit" :placeholder="$t('project.invoicedUnit')"></el-input>
      </el-form-item>

      <!-- 税号 -->
      <el-form-item prop="tin" :label="$t('project.tin') + labelSuffix">
        <div v-if="isDetail">{{ dataForm.tin }}</div>

        <el-input v-else v-model="dataForm.tin" :placeholder="$t('project.tin')"></el-input>
      </el-form-item>

      <!-- 详细地址 -->
      <el-form-item prop="address" :label="$t('project.address') + labelSuffix">
        <div v-if="isDetail">{{ dataForm.address }}</div>
        <el-input v-else v-model="dataForm.address" :placeholder="$t('project.address')"></el-input>
      </el-form-item>

      <!-- 项目开展次数 -->
      <el-form-item prop="launchNumber" :label="$t('project.launchNumber') + labelSuffix">
        <div v-if="isDetail">{{ dataForm.launchNumber }}</div>
        <el-input v-else v-model="dataForm.launchNumber" type="number" :placeholder="$t('project.launchNumber')"></el-input>
      </el-form-item>

      <!-- 所属机构 -->
      <el-form-item prop="dept" :label="$t('project.dept') + labelSuffix">
        <div v-if="isDetail">{{ dataForm.fullDeptName }}</div>
        <el-cascader v-else ref="deptRef" v-model="dataForm.fullDeptId" @change="onDeptChange" :placeholder="$t('project.dept')" filterable clearable :props="{ label: 'name', value: 'id', checkStrictly: true }" :options="deptList" />
      </el-form-item>

      <!-- 备注 -->
      <el-form-item prop="notes" class="notes" :label="$t('project.notes') + labelSuffix">
        <div v-if="isDetail">{{ dataForm.notes }}</div>
        <el-input v-else v-model="dataForm.notes" :autosize="{ minRows: 3, maxRows: 6 }" type="textarea" :placeholder="$t('project.notes')"></el-input>
      </el-form-item>
    </el-form>
    <template v-slot:footer v-if="isDetail">
      <el-button @click="visible = false">{{ $t("close") }}</el-button>
    </template>
    <template v-else v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { computed, ref } from "vue";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
import baseService from "@/service/baseService";
import { isMobile, getNestedStructure } from "@/utils/utils";
import { IObject } from "@/types/interface";

const { t } = useI18n();

const emit = defineEmits(["refreshDataList"]);
const visible = ref(false);
const isDetail = ref(false);
const labelSuffix = computed(() => {
  return isDetail.value ? "：" : "";
});

const dataFormRef = ref();

type FormDataType = {
  id: string;
  name: string;
  fullAreaId: string[];
  fullAreaName?: string;
  area: { id: string; name: string };
  director: { id: string; name: string };
  directorConnect: string;
  price: string | number;
  invoicedUnit: string;
  tin: string;
  address: string;
  launchNumber: string | number;
  fullDeptId: string[];
  fullDeptName: string;
  dept: { id: string; name: string };
  notes: string;
};
const dataForm = ref<FormDataType>({
  id: "",
  name: "",
  fullAreaId: [],
  fullAreaName: "",
  area: { id: "", name: "" },
  director: { id: "", name: "" },
  directorConnect: "",
  price: "",
  invoicedUnit: "",
  tin: "",
  address: "",
  launchNumber: "",
  fullDeptId: [],
  fullDeptName: "",
  dept: { id: "", name: "" },
  notes: ""
});

const isEdit = computed(() => {
  return !!dataForm.value.id;
});

// 负责人
const directorList = ref<{ id: string; name: string }[]>([]);
const getDirectorList = () => {
  baseService.get("/sys/user/list").then((res) => {
    directorList.value = res.data?.map(({ id, realName }: { id: string; realName: string }) => {
      return { id, name: realName };
    });
  });
};
getDirectorList();

// 所属机构
const deptList = ref<{ id: string; name: string }[]>([]);
const getDeptList = () => {
  baseService.get("/sys/dept/list").then((res) => {
    deptList.value = res.data || [];
  });
};
getDeptList();

// 机构选择change
const deptRef = ref();
const onDeptChange = () => {
  // 获取选中的节点
  const [{ text, value }] = deptRef.value.getCheckedNodes();
  dataForm.value.dept = {
    id: value + "",
    name: text
  };
};

// 所属区域
const areaList = ref<{ id: string; name: string }[]>([]);
const getAreaList = () => {
  baseService.get("/sys/region/child/tree").then((res) => {
    areaList.value = getNestedStructure(res?.data?.[0].children, 4, { keyName: "name", valueName: "id" }) || [];
  });
};
getAreaList();

// 区域选择change
const areaRef = ref();
const onAreaChange = () => {
  console.log("aearFull==", dataForm.value.fullAreaId);
  console.log("areaRef.value.getCheckedNodes()==", areaRef.value.getCheckedNodes());
  // 获取选中的节点
  const [{ text, value }] = areaRef.value.getCheckedNodes();
  dataForm.value.area = {
    id: value + "",
    name: text
  };
};

// 初始化
const init = (row: any, type: string) => {
  visible.value = true;
  isDetail.value = type === "detail";
  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }
  const {
    id = "",
    name = "",

    director = "",
    directorName = "",

    fullAreaId = "",
    fullAreaName = "",
    areaId = "",
    directorConnect,
    price,
    invoicedUnit,
    tin,
    address,
    launchNumber = "",
    fullDeptId,
    fullDeptName,
    deptId = "",
    notes
  } = row;
  dataForm.value = {
    id,
    name,
    fullAreaId: fullAreaId ? fullAreaId.split(",") : [],
    fullAreaName,
    area: {
      id: areaId,
      name: fullAreaName
    },
    director: {
      id: director,
      name: directorName
    },
    directorConnect,
    price,
    invoicedUnit,
    tin,
    address,
    launchNumber,
    fullDeptId: fullDeptId ? fullDeptId.split(",") : [],
    dept: {
      id: deptId + "",
      name: fullDeptName
    },
    fullDeptName,
    notes
  };
};
const validateMobile = (rule: IObject, value: string, callback: (e?: Error) => any) => {
  if (!isMobile(value)) {
    return callback(new Error(t("validate.format", { attr: t("project.directorConnect") })));
  }
  callback();
};

const rules = ref({
  name: [{ required: true, message: t("validate.required"), trigger: ["blur", "change"] }],
  directorConnect: [{ validator: validateMobile, trigger: ["blur", "change"] }]
});

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }

    const { id, name, price, director, launchNumber, address, tin, fullAreaId, area, directorConnect, fullDeptId, dept, invoicedUnit, notes } = dataForm.value;
    const params = {
      id,
      name,

      areaId: area.id,
      fullAreaId: fullAreaId.join(","),
      fullAreaName: area.name,

      director: director.id,
      directorName: director.name,
      directorConnect,
      price,
      invoicedUnit,
      tin,
      address,
      launchNumber,

      deptId: dept.id,
      fullDeptId: fullDeptId.join(","),
      fullDeptName: dept.name,

      notes
    };

    console.log("params=", params);

    (dataForm.value.id ? baseService.put : baseService.post)("/assess/assessproject", params).then((res) => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

defineExpose({
  init
});
</script>
<style lang="less" scoped>
.el-form {
  &.isDetail {
    :deep(.el-form-item__label:before) {
      display: none;
    }
  }
}
:deep(.el-form-item) {
  width: calc(50% - 16px);
  .el-cascader {
    width: 100%;
  }
  &.notes {
    width: 100%;
  }
}
</style>
